﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using System.Text.RegularExpressions;
using TST.SharePoint.Shared;
using System.Collections.ObjectModel;
using TST.SharePoint.Shared.Datasource;

namespace TST.WebParts
{
    public static class ListSupport
    {
        public static SPList GetList(string url)
        {
            string selectedListUrl = System.Web.HttpUtility.UrlDecode(url);
            if (!selectedListUrl.StartsWith("/"))
            {
                selectedListUrl = "/" + url;
            }
            string listName = selectedListUrl.Substring(selectedListUrl.LastIndexOf("/") + 1);
            string siteUrl = selectedListUrl.Substring(0, selectedListUrl.LastIndexOf("/"));// + 1);
            string webAppUrl = SPContext.Current.Site.Url;
            if (SPContext.Current.Site.ServerRelativeUrl != "/")
            {
                webAppUrl = SPContext.Current.Site.Url.ToLower().Replace(SPContext.Current.Site.ServerRelativeUrl.ToLower(), string.Empty);
            }
            using (SPSite site = new SPSite(string.Format("{0}{1}", webAppUrl, siteUrl)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    foreach (SPList list in web.Lists)
                    {
                        if (string.Compare(list.RootFolder.Name, listName, true) == 0)
                        {
                            return list;
                        }
                        if (string.Compare(list.Title, listName, true) == 0)
                        {
                            return list;
                        }
                    }
                }
            }
            return null;
        }

        internal static List<KeyValuePair<string, string>> GetListItems(SPList itemList, string displayField, string valueField, Microsoft.SharePoint.WebPartPages.IFilterValues filterValues)
        {
            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();
            if (itemList != null && itemList.Fields.ContainsField(displayField) && itemList.Fields.ContainsField(valueField))
            {
                SPQuery query = new SPQuery();
                query.ViewFields = string.Format("<FieldRef Name=\"{0}\" /><FieldRef Name=\"{1}\" />", displayField, valueField);
                string where = string.Empty;
                if (filterValues!=null &&
                    !string.IsNullOrEmpty(filterValues.ParameterName) &&
                    filterValues.ParameterValues != null &&
                    filterValues.ParameterValues.Count > 0)
                {
                    if (itemList.Fields.ContainsField(filterValues.ParameterName))
                    {
                        where = GetCAML(itemList, filterValues.ParameterName, filterValues.ParameterValues);
                        if (string.IsNullOrEmpty(where))
                        {
                            return result;
                        }
                        else
                        {
                            where = string.Format("<Where>{0}</Where>", where);
                        }
                    }
                    else
                    {
                        return result;
                    }
                }
                query.Query = string.Format("{0}<OrderBy><FieldRef Name=\"{1}\" Ascending=\"TRUE\"/></OrderBy>", where, displayField);
                SPListItemCollection items = itemList.GetItems(query);
                foreach (SPListItem item in items)
                {
                    if (item[displayField] != null && item[valueField] != null)
                    {
                        string displayValue = GetDisplayValue(item, displayField);
                        string value = GetFieldValue(item, valueField);
                        string text = displayValue;
                        if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(text))
                        {
                            result.Add(new KeyValuePair<string, string>(value, text));
                        }
                    }
                }
                return result;
            }
            return result;
        }

        internal static string GetCAML(SPList itemList, string fieldName, ReadOnlyCollection<string> filterValues)
        {
            SPField field = itemList.Fields[fieldName];

            Field fld = FieldFactory.GetField(field);
            Filters filters = new Filters();
            Filter filter = new Filter(fld);
            filter.FilterOperand = FilterOperand.Or;
            foreach (string val in filterValues)
            {
                if (!string.IsNullOrEmpty(val))
                {
                    filter.FilterValues.Add(new FilterValue(val));
                }
            }
            filters.Add(filter);
            return FiltersToCAML.GetCAML(filters);
        }

        private static string GetDisplayValue(SPListItem item, string fieldName)
        {
            SPField field = item.ParentList.Fields.GetFieldByInternalName(fieldName);
            Field typed = FieldFactory.GetField(field);
            return typed.GetTypedValueFormatted(item[fieldName]);
        }

        private static string GetFieldValue(SPListItem item, string fieldName)
        {
            SPField field = item.ParentList.Fields.GetFieldByInternalName(fieldName);
            Field typed = FieldFactory.GetField(field);
            return typed.GetTypedValueAsString(item[fieldName]);
        }


        internal static SPFolder GetStyleFolder(SPSite site)
        {
            if (site==null)
                return null;
            SPWeb rootWeb = site.RootWeb;
            try
            {
                foreach (SPList list in rootWeb.Lists)
                {
                    if (list is SPDocumentLibrary && string.Compare(list.RootFolder.Name, "Style Library", true) == 0)
                    {
                        SPDocumentLibrary styleLibrary = list as SPDocumentLibrary;
                        foreach (SPFolder folder in styleLibrary.RootFolder.SubFolders)
                        {
                            if (string.Compare(folder.Name, "TST", true) == 0)
                            {
                                return folder;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (SPContext.Current.Web.ID != rootWeb.ID)
                {
                    rootWeb.Dispose();
                }
            }
            return null;
        }
    }
}
